package cn.szzsi.interceptor;

/**
 * Created by haotian on 2016/12/8.
 */

import cn.szzsi._Config;
import cn.szzsi.common.kit.CommonUtil;
import cn.szzsi.common.model.Member;
import cn.szzsi.common.model.SiteConfig;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.kit.HttpKit;
import com.jfinal.kit.StrKit;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

public class WechatLoginInterceptor implements Interceptor {
    private String appid;//微信应用id
    private String secret;//微信应用秘钥
    private static final String AUTHORIZE_URL = "https://open.weixin.qq.com/connect/oauth2/authorize";
    private static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/sns/oauth2/access_token";
    private static final String USER_INFO_URL = "https://api.weixin.qq.com/sns/userinfo";

    public void intercept(Invocation ai) {
        Controller c = ai.getController();
        if(isNeedWechatLogin(c)){
            if (!weixinLogin(c)) {
                return;//获取code并且未登录成功时,中断当前操作流程
            }
        }
        ai.invoke();
    }

    /**
     * 是否需要微信登录的判断条件：
     * 1、微信浏览器
     * 2、用户session不存在
     * 3、系统配置中开启微信登录授权
     * @param c
     * @return
     */
    public boolean isNeedWechatLogin(Controller c){
        boolean flag = false;
        if(CommonUtil.isWeixinBrowser(c)){//是否微信浏览器
            c.setAttr(CommonUtil.BROWSER_TYPE,"weixinBrowser");
            String loginMemberId = c.getSessionAttr(Member.LOGIN_MEMBER_ID_SESSION_NAME);//获取当前登录用户
            if(StrKit.isBlank(loginMemberId)){
                flag = true;
            }
        }
        return flag;
    }

    /**
     * 微信登录
     * 1，获取code之前
     * 2，获取code之后
     * @param c
     * @return
     */
    private boolean weixinLogin(Controller c){
        boolean flag = false;
        String code =c.getPara("code");
        appid= _Config.p.get("wechat_appid");
        secret=_Config.p.get("wechat_secret");
        if(StrKit.isBlank(code)){//code为null
            String redirect_uri= "";
            String fansIndexUrl= CommonUtil.getBackUrl(c);
            try {
                redirect_uri = URLEncoder.encode(fansIndexUrl,"utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            String authUrl=AUTHORIZE_URL+"?appid="+appid+"&redirect_uri="+redirect_uri+"&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
            c.redirect(authUrl);
        }else{
            //已经获取到code,根据code取access_token
            String reqUrl=ACCESS_TOKEN_URL+"?APPID="+appid+"&secret="+secret+"&code="+code+"&grant_type=authorization_code";
            String result= HttpKit.get(reqUrl);
            JSONObject obj = JSON.parseObject(result);
            String access_token=obj.getString("access_token");
            if(StrKit.notBlank(access_token)){
                String openid = obj.getString("openid");
                Member member = Member.dao.isExistByOpenid(openid);
                if (member != null) {//判断用户是否绑定手机号,如果未绑定,提醒用户绑定手机号
                    if(StrKit.isBlank(member.getPhone())){//之前注册的用户没有绑定手机号,提醒用户绑定手机号
                        c.setSessionAttr("member",member);
                        c.render("/template/default/html/binding_phone_login.html");
                        return false;
                    }else{
                        c.setSessionAttr(Member.LOGIN_MEMBER_ID_SESSION_NAME, member.getId());// 写入会员登录Session
                        c.setAttr("loginMember", member);
                    }
                } else {//用户未存在拉取用户信息-->新用户
                    String getUserInfo = USER_INFO_URL+"?access_token=" + access_token + "&openid=" + openid + "&lang=zh_CN";
                    String resultUserInfo = HttpKit.get(getUserInfo);
                    JSONObject userJson = JSON.parseObject(resultUserInfo);
                    //获取unionid,判断是否通过其他渠道注册
                    String unionid=userJson.getString("unionid");
                    Member memberByUnionid=Member.dao.getByUnionid(unionid);
                    if(memberByUnionid!=null && StrKit.notBlank(memberByUnionid.getPhone())){
                        String nickname = userJson.getString("nickname");
                        String sex = userJson.getString("sex");
                        String country = userJson.getString("country");
                        String province = userJson.getString("province");
                        String city = userJson.getString("city");
                        String headimgurl = userJson.getString("headimgurl");
                        memberByUnionid.setUsername(nickname);
                        memberByUnionid.setSex(sex);
                        memberByUnionid.setCountry(country);
                        memberByUnionid.setProvince(province);
                        memberByUnionid.setCity(city);
                        memberByUnionid.setHeadimgurl(headimgurl);
                        memberByUnionid.setOpenid(openid);
                        memberByUnionid.update();
                    }else{
                        userJson.put("openid",openid);
                        //保存用户信息之前,先让用户绑定手机号
                        c.setSessionAttr(Member.USER_JSON,userJson);
                        c.render("/template/default/html/binding_phone_register.html");
                        return false;
                    }

                }
                flag = true;
            }else{
                c.render("/html/404.html");
            }
        }
        return flag;
    }
}
